package firstping.controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import firstping.data.QnAPersistenceManager;
import firstping.model.Customer;
import firstping.model.Domain;
import firstping.string.Utils;

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		String[] check = new String[5];
		req.setAttribute("check", check);
		
		req.setAttribute("title", "Register account");
		req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site");
		req.setAttribute("description", "Register account.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
		
		try {
			req.getRequestDispatcher("/register.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html");
		resp.getWriter().println("Register success");
		
		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		
		String email   = req.getParameter("email");
		String pwd     = req.getParameter("pwd");
		String re_pwd  = req.getParameter("re_pwd");
		String website = req.getParameter("website");
		
		String[] check = new String[5];
		
	    java.util.regex.Pattern p = java.util.regex.Pattern.compile(".+@.+\\.[a-z]+");
	    Matcher m = p.matcher(email);
	    boolean matchFound = m.matches();

	    if (!matchFound)
	    {
	    	check[0] = "Invalid Email";
	    } else {
	    	Query query1 = psm.newQuery(Customer.class);
	    	query1.setFilter("email=='"+email+"'");
	    	@SuppressWarnings("unchecked")
			List<Customer> cuss = (List<Customer>) query1.execute();
	    	
	    	if(cuss.size() > 0)
	    	{
	    		check[0] = "Email already exists !";
	    	}
	    }
		
	    if(pwd == null || (pwd != null && pwd.equals("")))
	    {
	    	check[1] = "Password is not empty";
	    } else {
	    	if(!pwd.equals(re_pwd))
	    	{
	    		check[2] = "Confirmation of wrong password";
	    	}
	    }
	    
	    p = java.util.regex.Pattern.compile("http://[\\w.]+[.][a-z]+$");
	    m = p.matcher(website);
	    matchFound = m.matches();
	    
	    if (!matchFound)
	    {
	    	check[3] = "Website must have the form http://...";
	    }
	    
	    //check capchar
		String remoteAddr = req.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6Lf59ccSAAAAANK1ZHc5x_r4dfk6mZQTEJCvjFlo");

        String challenge = req.getParameter("recaptcha_challenge_field");
        String uresponse = req.getParameter("recaptcha_response_field");
        if(challenge == null)
        {
        	challenge = "b";
        }
        if(uresponse == null)
        {
        	uresponse = "a";
        }
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
        	check[4] = "Invalid Captcha";
        }
	    
	    if(check[0] == null && check[1] == null && check[2] == null && check[3] == null && check[4] == null)
	    {
	    	Customer customer = new Customer();
	    	customer.setEmail(email);
	    	customer.setPassword(pwd);
	    	customer.setType("Trial");
	    	customer.setRequest(10);
	    	customer.setStatus(0);
	    	try {
				customer.setMd5(Utils.md5(email));
			} catch (NoSuchAlgorithmException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	    	Date update = new Date();
	    	Date endDate = new Date(update.getTime()+15*24*60*60*1000);
	    	customer.setEndDate(endDate);
	    	customer.setNumber(1);
	    	psm.makePersistent(customer);
	    	
	    	Properties props = new Properties();
	        Session sessions = Session.getDefaultInstance(props, null);

	        String emails = "Firstping.com support";
	        String text = "Click the link bellow to confirm your email address : <br/><br/>";

			try {
				text += "http://www.firstping.com/active?active="+Utils.md5(email);
			} catch (NoSuchAlgorithmException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
	        text += "<br/><br/>You will be asked to log into your account to confirm this email address. Be sure to log in with your current primary email address.";
	        String msgBody = text;

	        try {
	            Message msg = new MimeMessage(sessions);
	            msg.setFrom(new InternetAddress("admin@firstping.com",emails));
	            msg.addRecipient(Message.RecipientType.TO,
	                             new InternetAddress(email,email));
	            msg.setSubject("Active account");
	            msg.setContent(msgBody, "text/html");
	            Transport.send(msg);
	           
	        } catch (AddressException e1) {
	            // ...
	        } catch (MessagingException e1) {
	            // ...
	        }
	    	
	    	
	    	Domain domain = new Domain();
	    	domain.setEmail(email);
	    	domain.setRequest(10);
	    	domain.setName(website);
	    	Date up = new Date(update.getTime()+10*60*1000);
	    	domain.setUpdate(up);
	    	domain.setLastUpdateDate(update);
	    	domain.setEndDate(endDate);
	    	domain.setStatus("True");
	    	domain.setActive("1");
	    	psm.makePersistent(domain);
	    	
	    	Query query = psm.newQuery(Customer.class);
	    	query.setFilter("email=='"+email+"'");
	    	@SuppressWarnings("unchecked")
			List<Customer> cus = (List<Customer>) query.execute();
	    	
	    	if(cus.size() > 0)
	    	{
				req.setAttribute("check", check);
				req.setAttribute("success", "Register successful. Free for the first 15 days. Please check the email to complete registration.");
			    req.setAttribute("email", email);
			    req.setAttribute("website", website);
			    req.setAttribute("title", "Register account");
				req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site");
				req.setAttribute("description", "Register account.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
				try {
					req.getRequestDispatcher("/register.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
	    } else {
		    req.setAttribute("check", check);
		    req.setAttribute("email", email);
		    req.setAttribute("website", website);
		    req.setAttribute("title", "Register account");
			req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site");
			req.setAttribute("description", "Register account.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
			try {
				req.getRequestDispatcher("/register.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	}
}
